/*
 * @Author: zhangyang
 * @Date: 2024-05-28 17:13:50
 * @LastEditTime: 2024-06-03 11:31:13
 * @Description: 
 * @LastEditors: zhangyang
 * ██████╗ ██╗     ██╗   ██╗███████╗███████╗██╗   ██╗ ██████╗ ██╗   ██╗███╗   ██╗ ██████╗               ██╗    ██╗███████╗██████╗ 
 * ██╔══██╗██║     ██║   ██║██╔════╝██╔════╝╚██╗ ██╔╝██╔═══██╗██║   ██║████╗  ██║██╔════╝               ██║    ██║██╔════╝██╔══██╗
 * ██████╔╝██║     ██║   ██║█████╗  ███████╗ ╚████╔╝ ██║   ██║██║   ██║██╔██╗ ██║██║  ███╗    █████╗    ██║ █╗ ██║█████╗  ██████╔╝
 * ██╔══██╗██║     ██║   ██║██╔══╝  ╚════██║  ╚██╔╝  ██║   ██║██║   ██║██║╚██╗██║██║   ██║    ╚════╝    ██║███╗██║██╔══╝  ██╔══██╗
 * ██████╔╝███████╗╚██████╔╝███████╗███████║   ██║   ╚██████╔╝╚██████╔╝██║ ╚████║╚██████╔╝              ╚███╔███╔╝███████╗██████╔╝
 * ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚══════╝   ╚═╝    ╚═════╝  ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝                ╚══╝╚══╝ ╚══════╝╚═════╝
 * Copyright (c) 2024 to current by BluesYoung-web, All Rights Reserved. 
 */
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '/database/categray.dart';
import '/routers/fluro_navigator.dart';
import '/routers/routers.dart';
import '/util/toast_utils.dart';

class CategrayList extends StatefulWidget {
  /// 每行显示的列数
  /// 默认4列
  final int gridColNum;

  /// 间隔
  /// 默认 0
  final double gridGap;

  /// 收入/支出
  final CategrayType type;

  final Function(ICategray)? onClickItem;

  const CategrayList(
      {super.key,
      this.gridColNum = 5,
      this.gridGap = 0,
      this.type = CategrayType.outcome,
      this.onClickItem});

  @override
  State<StatefulWidget> createState() => _CategrayListState();
}

class _CategrayListState extends State<CategrayList> {
  List<ICategray> _list = [];

  int _selectedIndex = 0;

  void getList() {
    DataBaseCategray.getAllCategray(widget.type).then((value) => {
          setState(() {
            _list = value;
            _selectedIndex = 0;
            widget.onClickItem?.call(_list[0]);
          })
        });
  }

  @override
  void initState() {
    super.initState();

    getList();
  }

  Widget _buildCategrayText(String name) {
    return Text(name, style: const TextStyle(fontSize: 12));
  }

  List<Widget> _buildCategrayList() {
    var list = List.generate(_list.length, (index) {
      var item = _list[index];

      return GestureDetector(
        child: Center(
            child: Column(
          children: [
            CircleAvatar(
              radius: 24,
              backgroundColor: _selectedIndex == index ? Colors.amber : null,
              child: Text(
                item.icon ?? item.name,
                style: const TextStyle(fontSize: 20),
              ),
            ),
            _buildCategrayText(item.name)
          ],
        )),
        onTap: () {
          debugPrint('click: ${item.name}');
          widget.onClickItem?.call(item);

          setState(() {
            _selectedIndex = index;
          });
        },
        onLongPress: () {
          showGeneralDialog(
              context: context,
              pageBuilder: (BuildContext buildContext,
                  Animation<double> animation,
                  Animation<double> secondaryAnimation) {
                return TDAlertDialog(
                  title: '删除分类',
                  content: '确定删除${item.name}吗？',
                  leftBtn: TDDialogButtonOptions(
                    title: '删除',
                    titleColor: Colors.white,
                    theme: TDButtonTheme.danger,
                    action: () async {
                      await DataBaseCategray.deleteCategray(item.autoid!);
                      Toast.show('删除成功!');
                      getList();
                    },
                  ),
                  rightBtn: TDDialogButtonOptions(
                    title: '取消',
                    titleColor: Colors.grey,
                    type: TDButtonType.ghost,
                    action: () {},
                  ),
                  showCloseButton: true,
                );
              });
        },
      );
    });

    // add add button
    list.add(GestureDetector(
      child: Center(
        child: Column(
          children: [
            const CircleAvatar(
              radius: 24,
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
              child: Icon(TDIcons.add),
            ),
            _buildCategrayText('添加分类')
          ],
        ),
      ),
      onTap: () {
        debugPrint('click add categray');
        NavigatorUtils.pushResult(context, Routes.categrayCreate, (result) {
          debugPrint('result: $result');
          getList();
        }, arguments: {'type': widget.type});
      },
    ));

    return list;
  }

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: widget.gridColNum,
      mainAxisSpacing: widget.gridGap,
      crossAxisSpacing: widget.gridGap,
      children: _buildCategrayList(),
    );
  }
}
